const userModel = require("../models/user");
const { encryptPassword } = require("../utils/crypto"); // 加密工具
const { generateToken } = require("./common");

exports.getUserInfo = async (options) => {
    // 1. 查数据库获取用户
    const userList = await userModel.findUserList(options);

    return { userList };
};

exports.login = async ({ code }) => {
    const wxUrl = `https://api.weixin.qq.com/sns/jscode2session?appid=wx39268561e231bae4&secret=8e4d8316313be540059103c28f5c431d&grant_type=authorization_code&js_code=${code}`;
    const { errcode, session_key, openid } = await fetch(wxUrl, {
        method: "GET"
    }).then((response) => {
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    });
    if (errcode) {
        ctx.status = 400;
        ctx.body = { code: 400, message: `微信接口错误: ${wxData.errmsg}` };
        return;
    }
    // 1. 查数据库获取用户
    await userModel.login({ openid, session_key });

    const token = await generateToken(openid); // 生成token
    return { token, openid };
};

exports.refreshToken = async ({ openid }) => {
    const token = await generateToken(openid); // 生成token

    return { token };
};
